# coding:utf-8
import sys


def lines(file):
    for line in open(file):
        yield line
    yield '\n'


def blocks(file):
    """
    读取PO文件，切割成一个个包含原文和译文的文本块
    """
    block = []
    for line in lines(file):
        if line.startswith('#'):
            continue
        if line.startswith('msgid') and block:
            yield ''.join(block).strip()
            block = []
        if line.strip():
            block.append(line)


def get_content(block):
    """
    从block中分析原文和译文，并以元组的形式返回
    """
    block_dec = block.decode('utf8')
    spl_index = block_dec.find('msgstr')
    content = (block_dec[:spl_index], block_dec[spl_index:])
    return content

def find_translation(msgid, source_file):
    """
    在资源文件中查找是否有指定的 msgid 块；
    有则返回 msgstr 块，无则返回空字符串
    """
    for source_block in blocks(source_file):
        source_content = get_content(source_block)
        if msgid == source_content[0] and \
            len(source_content[1]) >= len('msgstr ""'):
            return source_content[1]
    else:
        return ''


def process(proc_file, source_file):
    """
    处理po文件
    如果资源文件中有翻译，则输出 原文 + 译文
    如果没有翻译，则输出 原始块
    """
    for proc_block in blocks(proc_file):
        proc_content = get_content(proc_block)
        msgstr = find_translation(proc_content[0], source_file)
        if msgstr:
            yield ''.join([proc_content[0], msgstr])
        else:
            yield ''.join(proc_content)


def main():
    f = open('output.po', 'w')
    for block in process(sys.argv[1], sys.argv[2]):
        print block
        print ''
        f.write(block.encode('utf8'))
        f.write('\n\n')


if __name__ == '__main__':
    try:
        main()
    except IndexError:
        print 'Usage:'
        print '  python %s [process file path] [source file path]' \
               % sys.argv[0]
    else:
        print 'Unknown reason.'
